﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using AFS.VisitationRequestTool.Addin.Variables;
using AFS.VisitationRequestTool.Addin.Dictionary;
using Outlook = Microsoft.Office.Interop.Outlook;
using AFS.VisitationRequestTool.Addin.Common;
using Microsoft.Office.Interop.Outlook;
using AFS.VisitationRequestTool.Addin.Entities;
using Microsoft.Office.Tools.Outlook;


namespace AFS.VisitationRequestTool.Addin.Components
{
    /// <summary>
    /// This represents the actual form region for the visitation request embedded in a meeting outlook item type.
    /// Use this.OutlookItem to get a reference to the current Outlook item.
    //  Use this.OutlookFormRegion to get a reference to the form region.
    /// </summary>
    public partial class RequestDetailsFormRegion
    {
        // public event loadcomplete;

        // private VisitationRequestPresenter controller;

        private bool initialized;

        /// <summary>
        /// Indicates if form region has been initialized yet. Referenced in "Open/Close Visit" ribbon button click handler.
        /// </summary>
        public bool Initialized
        {
            get { return initialized; }
            set { initialized = value; }
        }

        #region Request Details Form Region Factory

        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Appointment)]
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass("IPM.Schedule.Meeting.Request")]
        [Microsoft.Office.Tools.Outlook.FormRegionName("AFS.VisitationRequestTool.Addin.Components.RequestDetailsFormRegion")]
        public partial class RequestDetailsFormRegionFactory
        {
            // Occurs before the form region is initialized.
            // To prevent the form region from appearing, set e.Cancel to true.
            // Use e.OutlookItem to get a reference to the current Outlook item.
            private void RequestDetailsFormRegionFactory_FormRegionInitializing(object sender, FormRegionInitializingEventArgs e)
            {
                Logger.Verbose("Entered");
                //System.Diagnostics.Debug.WriteLine(Microsoft.VisualBasic.Information.TypeName(e.OutlookItem));
                // Check to make sure we're dealing with an AppointmentItem type.
                //if (e.OutlookItem is Outlook.AppointmentItem)
                //{
                //    Outlook.AppointmentItem appointmentItem = (Outlook.AppointmentItem)e.OutlookItem;

                //    e.Cancel = false;
                //    InitializeAppointmentItemCustomProperties(appointmentItem);


                //    //if (appointmentItem.MeetingStatus == Outlook.OlMeetingStatus.olNonMeeting)
                //    //{
                //    //    e.Cancel = true;  // Cancel loading of form (will not appear).
                //    //}
                //    ////else
                //    //{
                //    //    e.Cancel = false;
                //    //    InitializeAppointmentItemCustomProperties(appointmentItem);
                //    //}

                //    Logger.Verbose(String.Format("AppointmentItem. e.Cancel-->{0}", e.Cancel.ToString()));
                //}
                //else if (e.OutlookItem is Outlook.MeetingItem)
                //{
                //    // Outlook.MeetingItem meetingItem = (Outlook.MeetingItem)e.OutlookItem;
                //    e.Cancel = false;
                //    InitializeAppointmentItemCustomProperties(((MeetingItem)e.OutlookItem).GetAssociatedAppointment(false));

                //    Logger.Verbose(String.Format("MeetingItem. e.Cancel-->{0}", e.Cancel.ToString()));
                //}
                if (e.OutlookItem is Outlook.AppointmentItem || e.OutlookItem is Outlook.MeetingItem)
                {
                    AppointmentItem appointmentItem;

                    if (e.OutlookItem is Outlook.AppointmentItem)
                        appointmentItem = (Outlook.AppointmentItem)e.OutlookItem;
                    else
                    {
                        MeetingItem meetingItem = (Outlook.MeetingItem)e.OutlookItem;
                        appointmentItem = meetingItem.GetAssociatedAppointment(false);
                    }

                    if (appointmentItem != null)
                    {
                        //InitializeAppointmentItemCustomProperties(appointmentItem);
                        e.Cancel = false;
                    }
                    else
                        e.Cancel = true;
                }
                else
                {
                    e.Cancel = true;
                    Logger.Verbose(String.Format("Unknown item type. e.Cancel-->{0}", e.Cancel.ToString()));
                }
            }


        }

        #endregion

        #region Public Methods

        public void Initialize(AppointmentItem appointmentItem)
        {
            InitializeAppointmentItemCustomProperties(appointmentItem);
            InitializeFormRegionFields(appointmentItem);

            if (lstVisitType.SelectedIndex > -1)
                DisableControlsCheck(appointmentItem);

            SetupTabView();
            initialized = true;
        }

        public void Initialize(MeetingItem meetingItem)
        {
            AppointmentItem appointmentItem = meetingItem.GetAssociatedAppointment(false);
            Initialize(appointmentItem);
        }

        public void SaveRequestDetailsToLocalOutlookItemProperties()
        {
            if (this.OutlookItem is Outlook.AppointmentItem)
            {
                Outlook.AppointmentItem appointmentItem = (Outlook.AppointmentItem)this.OutlookItem;

                // Checking if organizer already cancelled meeting. If so, then no need to update apppoint item properties.
                if (appointmentItem.MeetingStatus != Outlook.OlMeetingStatus.olMeetingCanceled)
                {
                    // Select Visit Type Tab
                    appointmentItem.ItemProperties[Property.RequestSubmitted].Value = chkSubmitted.Checked; // Hidden // NOTE: is this necessary now considering we're using hidden file field?
                    appointmentItem.ItemProperties[Property.Filename].Value = txtFileName_Hidden.Text; // Hidden
                    appointmentItem.ItemProperties[Property.VisitType].Value = lstVisitType.SelectedItem;
                    appointmentItem.ItemProperties[Property.NonAFSPersonnel].Value = txtNonAFSPersonnel.Text; // Hidden
                    appointmentItem.ItemProperties[Property.NonAFSPersonnelSocial].Value = txtSocialNonAFSPersonnel.Text; // Hidden

                    // One Time/Short Term/Recurring Visit Request Tab
                    appointmentItem.ItemProperties[Property.ReasonForVisit].Value = txtReason.Text;
                    appointmentItem.ItemProperties[Property.Impact].Value = txtImpact.Text;
                    appointmentItem.ItemProperties[Property.AgendaMaterials].Value = chkAgendaMaterials.Checked;
                    appointmentItem.ItemProperties[Property.RenewExistingVisit].Value = chkExistingVisit.Checked;
                    appointmentItem.ItemProperties[Property.SharePointAccessRequired].Value = ddSharePointAccess.SelectedItem;
                    //appointmentItem.ItemProperties[Property.PreviousVisitID].Value = txtPreviousVisitId.Text;

                    // Social Visit Request
                    appointmentItem.ItemProperties[Property.ReasonForVisitSocial].Value = txtSocialReasonForVisit.Text;
                    //appointmentItem.ItemProperties[Property.ConfirmSensitiveInfoSocial].Value = ddConfirmNoSensitiveShared.SelectedItem;
                    appointmentItem.ItemProperties[Property.ConfirmSensitiveInfoExplanationSocial].Value = txtSocialBusinessExplanation.Text;

                    // Location controls shared on Request Tabs
                    if (lstVisitLocations.SelectedItems.Count > 0)
                        appointmentItem.ItemProperties[Property.VisitLocations].Value = Utility.GetArrayFromListbox(lstVisitLocations);
                    else if (lstSocialVisitLocations.SelectedItems.Count > 0)
                        appointmentItem.ItemProperties[Property.VisitLocations].Value = Utility.GetArrayFromListbox(lstSocialVisitLocations);

                    //if (lstAFSOffices.SelectedItems.Count > 0)
                    //    appointmentItem.ItemProperties[Property.AFSVisitLocation].Value = Utility.GetListFromListbox(lstAFSOffices);
                    //else if (lstSocialAFSOffices.SelectedItems.Count > 0)
                    //    appointmentItem.ItemProperties[Property.AFSVisitLocation].Value = Utility.GetListFromListbox(lstSocialAFSOffices);
                    if (ddAFSOffices.SelectedIndex > -1)
                        appointmentItem.ItemProperties[Property.AFSVisitLocation].Value = Utility.GetStringValueFromObject(ddAFSOffices.SelectedItem);
                    else if (ddSocialAFSOffices.SelectedIndex > -1)
                        appointmentItem.ItemProperties[Property.AFSVisitLocation].Value = Utility.GetStringValueFromObject(ddSocialAFSOffices.SelectedItem);

                    if (ddForeignNationalYesOrNo.SelectedIndex > -1)
                        appointmentItem.ItemProperties[Property.ForeignNationalYesNo].Value = Utility.GetStringValueFromObject(ddForeignNationalYesOrNo.SelectedItem);
                    else if (ddSocialForeignNationalYesOrNo.SelectedIndex > -1)
                        appointmentItem.ItemProperties[Property.ForeignNationalYesNo].Value = Utility.GetStringValueFromObject(ddSocialForeignNationalYesOrNo.SelectedItem);

                    if (!String.IsNullOrEmpty(txtForeignNationalEmail.Text))
                        appointmentItem.ItemProperties[Property.ForeignNationalNames].Value = txtForeignNationalEmail.Text;
                    else if (!String.IsNullOrEmpty(txtSocialForeignNationalEmail.Text))
                        appointmentItem.ItemProperties[Property.ForeignNationalNames].Value = txtSocialForeignNationalEmail.Text;

                    chkSaved.Checked = true;

                    Logger.Verbose("Saved details to appointment item");
                }
            }
            //else
            //    throw new ApplicationException("Item is not an appointment type.");
        }

        public StringBuilder HaveAllRequiredFieldsEnteredInRequestForm()
        {
            Logger.Verbose("Entered");

            StringBuilder errorMessages = new StringBuilder();

            if (lstVisitType.SelectedItems.Count == 0)
            {
                errorMessages.AppendLine(ErrorMessages.ErrorMessageListBoxRequestTypeMissing);
                errorMessages.AppendLine();
            }

            if (lstVisitType.SelectedItem != null && lstVisitType.SelectedItem.ToString() != "Social Visit Request")
            {
                if (String.IsNullOrEmpty(txtReason.Text))
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxReasonEmpty);
                    errorMessages.AppendLine();
                }

                if (String.IsNullOrEmpty(txtImpact.Text))
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxImpactEmpty);
                    errorMessages.AppendLine();
                }

                if (lstVisitLocations.SelectedItems.Count == 0)
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageListBoxVisitLocationsEmpty);
                    errorMessages.AppendLine();
                }

                if (ddSharePointAccess.SelectedIndex < 0)
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageComboBoxSharePointAccessRequired);
                    errorMessages.AppendLine();
                }

                if (lstVisitLocations.SelectedItems.Contains("AFS Office"))
                {
                    if (ddAFSOffices.SelectedIndex < 0)
                    {
                        errorMessages.AppendLine(ErrorMessages.ErrorMessageDropDownAFSLocationEmpty);
                        errorMessages.AppendLine();
                    }
                    if (ddForeignNationalYesOrNo.SelectedIndex < 0)
                    {
                        errorMessages.AppendLine(ErrorMessages.ErrorMessageDropDownForeignNationalEmpty);
                        errorMessages.AppendLine();
                    }
                    else if (String.Equals(ddForeignNationalYesOrNo.SelectedItem.ToString(), "Yes", StringComparison.OrdinalIgnoreCase) && String.IsNullOrEmpty(txtForeignNationalEmail.Text))
                    {
                        errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxForeignNationalEmailEmpty);
                        errorMessages.AppendLine();
                    }
                }
            }
            else
            {
                if (String.IsNullOrEmpty(txtSocialReasonForVisit.Text))
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxSocialReasonForVisitEmtpy);
                    errorMessages.AppendLine();
                }

                if (String.IsNullOrEmpty(txtSocialBusinessExplanation.Text))
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxSocialBusinessExplanationEmpty);
                    errorMessages.AppendLine();
                }

                if (lstSocialVisitLocations.SelectedItems.Count == 0)
                {
                    errorMessages.AppendLine(ErrorMessages.ErrorMessageListBoxVisitLocationsEmpty);
                    errorMessages.AppendLine();
                }

                if (lstSocialVisitLocations.SelectedItems.Contains("AFS Office"))
                {
                    if (ddSocialAFSOffices.SelectedIndex < 0)
                    {
                        errorMessages.AppendLine(ErrorMessages.ErrorMessageDropDownAFSLocationEmpty);
                        errorMessages.AppendLine();
                    }
                    if (ddSocialForeignNationalYesOrNo.SelectedIndex < 0)
                    {
                        errorMessages.AppendLine(ErrorMessages.ErrorMessageDropDownForeignNationalEmpty);
                        errorMessages.AppendLine();
                    }
                    else if (String.Equals(ddSocialForeignNationalYesOrNo.SelectedItem.ToString(), "Yes", StringComparison.OrdinalIgnoreCase) && String.IsNullOrEmpty(txtSocialForeignNationalEmail.Text))
                    {
                        errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxForeignNationalEmailEmpty);
                        errorMessages.AppendLine();
                    }
                }

                //if (ddConfirmNoSensitiveShared.SelectedIndex < 0)              
                //    errorMessages.AppendLine(ErrorMessages.ErrorMessageDropDownConfirmSensitiveInformationEmpty);                

                //else
                //{
                //    if (String.Compare(ddConfirmNoSensitiveShared.SelectedItem.ToString(), "Will be Shared", true) == 0)
                //    {
                //        if (String.Compare(txtBusinessSharedExplanation.Text, String.Empty) == 0)
                //        {
                //            errorMessages.AppendLine(ErrorMessages.ErrorMessageTextBoxBusinessSharedInformationEmpty);
                //        }
                //    }
                //}
            }

            return errorMessages;
        }

        public void RemoveAppointmentItemCustomProperties(AppointmentItem appointmentItem)
        {
            for (int i = 1; i <= appointmentItem.UserProperties.Count; i++)
            {
                appointmentItem.UserProperties.Remove(i);
            }
        }
        #endregion

        #region Private initialization helper methods
        private void InitializeAppointmentItemCustomProperties(AppointmentItem appointmentItem)
        {
            try
            {
                appointmentItem.PropertyChange += new ItemEvents_10_PropertyChangeEventHandler(AppointmentItem_PropertyChange);
                Dictionary<string, Outlook.OlUserPropertyType> propertiesDetailsDictionary = DictionaryFactory.GetPropertyItemsDictionary();

                Logger.Info("Entered InitializeAppointmentItemCustomProperties");

                foreach (string propertyKey in propertiesDetailsDictionary.Keys)
                {
                    if (appointmentItem.ItemProperties[propertyKey] == null)
                    {
                        try
                        {
                            appointmentItem.ItemProperties.Add(propertyKey, propertiesDetailsDictionary[propertyKey], false, 1);
                        }
                        catch (System.Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            MessageBox.Show(ErrorMessages.ProgramException);
                        }
                        finally
                        {
                            Logger.Info(String.Format("Initialized null user property: {0}", appointmentItem.ItemProperties[propertyKey].Name));

                            if (appointmentItem.ItemProperties[propertyKey] != null) // QUESTION: Why is this in Finally clause in this case? Shouldn't this be part of Exception Handling routine?
                            {
                                Marshal.ReleaseComObject(appointmentItem.ItemProperties[propertyKey]);
                            }
                        }
                    }

                    Logger.Info("\tValue for {0}:{1}", propertyKey, appointmentItem.ItemProperties[propertyKey].Value);
                }

                Logger.Info("\n");

                Logger.Verbose(String.Format("Finished initializing {0} appointmentItem.UserProperties", appointmentItem.UserProperties.Count.ToString()));
            }

            catch (System.Exception ex)
            {
                Logger.Error(ex.ToString());
                MessageBox.Show(ErrorMessages.ProgramException);
            }

            finally
            {
                if (appointmentItem.ItemProperties != null)
                {
                    Logger.Verbose("Marshal.ReleaseComObject release appointmentItem.ItemProperties");
                    Marshal.ReleaseComObject(appointmentItem.ItemProperties);  // QUESTION: Are we releasing because we've effectively transfered objects to CLR?
                }
            }
        }      

        private void InitializeFormRegionFields(Outlook.AppointmentItem appointmentItem)
        {
            //// Select Visit Type tab form values
            lstVisitType.SelectedItem = appointmentItem.ItemProperties[Property.VisitType].Value;
            chkSubmitted.Checked = (bool)appointmentItem.ItemProperties[Property.RequestSubmitted].Value; // Hidden
            txtFileName_Hidden.Text = (string)appointmentItem.ItemProperties[Property.Filename].Value; // Hidden
            txtNonAFSPersonnel.Text = (string)appointmentItem.ItemProperties[Property.NonAFSPersonnel].Value; // Hidden
            txtSocialNonAFSPersonnel.Text = (string)appointmentItem.ItemProperties[Property.NonAFSPersonnelSocial].Value; // Hidden          

            // Location values could be associated with either one time or social visits
            if (lstVisitType.SelectedIndex == 0) // One Time/Short Term/Recurring Visit Request selected
            {
                // One Time/Short Term/Recurring Visit Request tab form values
                txtReason.Text = (string)appointmentItem.ItemProperties[Property.ReasonForVisit].Value;
                txtImpact.Text = (string)appointmentItem.ItemProperties[Property.Impact].Value;
                chkAgendaMaterials.Checked = (bool)appointmentItem.ItemProperties[Property.AgendaMaterials].Value;
                chkExistingVisit.Checked = (bool)appointmentItem.ItemProperties[Property.RenewExistingVisit].Value;

                // TODO: Fix sporatic casting exception string --> string[]
                foreach (string value in (string[])appointmentItem.ItemProperties[Property.VisitLocations].Value)
                    lstVisitLocations.SelectedItem = value;

                ddAFSOffices.SelectedItem = appointmentItem.ItemProperties[Property.AFSVisitLocation].Value;
                //foreach (string value in (string[])appointmentItem.ItemProperties[Property.AFSVisitLocation].Value)
                //    lstAFSOffices.SelectedItem = value;

                ddSocialForeignNationalYesOrNo.SelectedItem = appointmentItem.ItemProperties[Property.ForeignNationalYesNo].Value;
                txtSocialForeignNationalEmail.Text = (string)appointmentItem.ItemProperties[Property.ForeignNationalNames].Value;

                ddSharePointAccess.SelectedItem = appointmentItem.ItemProperties[Property.SharePointAccessRequired].Value;
                //chkSharePointAccess.Enabled = 
                //(appointmentItem.ItemProperties[Property.SharePointAccessRequired].Value != null ? (appointmentItem.ItemProperties[Property.SharePointAccessRequired].Value.ToString() == "Yes" ? true : false) : false);

                Logger.Verbose("Initialized 'One Time/Short Term/Recurring Visit Request' tab form");
            }
            else if (lstVisitType.SelectedIndex == 1)
            {
                // Social Visit tab form values            
                txtSocialReasonForVisit.Text = (string)appointmentItem.ItemProperties[Property.ReasonForVisitSocial].Value;
                txtSocialBusinessExplanation.Text = (string)appointmentItem.ItemProperties[Property.ConfirmSensitiveInfoExplanationSocial].Value;
                // TODO: Fix sporatic casting exception string --> string[]
                foreach (string value in (string[])appointmentItem.ItemProperties[Property.VisitLocations].Value)
                    lstSocialVisitLocations.SelectedItem = value;

                ddSocialAFSOffices.SelectedItem = appointmentItem.ItemProperties[Property.AFSVisitLocation].Value;

                //foreach (string value in (string[])appointmentItem.ItemProperties[Property.AFSVisitLocation].Value)
                //    lstSocialAFSOffices.SelectedItem = value;

                ddSocialForeignNationalYesOrNo.SelectedItem = appointmentItem.ItemProperties[Property.ForeignNationalYesNo].Value;
                txtSocialForeignNationalEmail.Text = (string)appointmentItem.ItemProperties[Property.ForeignNationalNames].Value;

                Logger.Verbose("Initialized 'Social Visit' tab form");
            }
        }

        private void SetupTabView()
        {
            switch (lstVisitType.SelectedIndex)
            {
                case 0:
                    TabCtrl.TabPages.Remove(this.TabPage3);
                    TabPage2.Show();
                    TabCtrl.SelectTab(General.TabIndexTwo);
                    break;
                case 1:
                    TabCtrl.TabPages.Remove(this.TabPage2);
                    TabPage3.Show();
                    TabCtrl.SelectTab(General.TabIndexThree);
                    break;
                default:
                    TabCtrl.TabPages.Remove(this.TabPage2);
                    TabCtrl.TabPages.Remove(this.TabPage3);
                    break;
            }
        }

        private void DisableControlsCheck(AppointmentItem appointmentItem)
        {
            Person currrentUser;
            AddressEntry organizer;

            organizer = appointmentItem.GetOrganizer();

            if (organizer != null && organizer.Name == appointmentItem.Session.CurrentUser.Name)
            {
                currrentUser = new MeetingOrganizer(appointmentItem.Session.CurrentUser);
            }
            else
            {
                currrentUser = new MeetingRecipient(appointmentItem.Session.CurrentUser);
            }

            if (String.IsNullOrEmpty(txtFileName_Hidden.Text) || !chkSubmitted.Checked) // Checking if hidden form field is populated, which indicates if InfoPath form data has already been submitted.
            {
                // If not organizer and non-AFS put fields in read-only and disable button.                 
                if (!(currrentUser is MeetingOrganizer) && currrentUser.AccountType != UserType.AFS)
                {
                    DisableFormControls();
                }
            }
            else // Form has been submitted already. Lock-down form fields and button.
            {
                DisableFormControls();
            }
        }

        public void DisableFormControls()
        {
            try
            {
                RibbonSubmitVR ribbon = Globals.Ribbons[Globals.ThisAddIn.Application.ActiveInspector()].Ribbon;

                if (ribbon == null)
                    ribbon = Globals.Ribbons.Ribbon;

                ribbon.btnUploadToSharepoint.Enabled = false;

                foreach (TabPage tabPage in this.TabCtrl.TabPages)
                {
                    foreach (Control control in tabPage.Controls)
                    {
                        if (control is TextBox || control is ListBox || control is ComboBox || control is CheckBox)
                            control.Enabled = false;
                    }
                }

                TabCtrl.TabPages.Remove(this.TabPage1);
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex.ToString());
                throw;
            }
        }
        #endregion

        #region Private event handling helper methods
        private void ShowAFSControls(bool showControls)
        {
            Logger.Verbose(String.Format("showControls->{0}", showControls.ToString()));

            lblAFSVisitLocations.Visible = showControls;
            ddAFSOffices.Visible = showControls;
            //lstAFSOffices.Visible = showControls;
            // ddAFSOffices.Visible = showControls;

            lblForeignNational.Visible = showControls;
            ddForeignNationalYesOrNo.Visible = showControls;

            lblForeignName.Visible = showControls;
            txtForeignNationalEmail.Visible = showControls;

            if (!showControls)
            {
                ddAFSOffices.SelectedIndex = -1;
                //lstAFSOffices.SelectedIndex = -1;
                ddForeignNationalYesOrNo.SelectedIndex = -1;
                txtForeignNationalEmail.Text = "";
            }
        }

        private void ShowAFSControlsSocial(bool showControls)
        {
            Logger.Verbose(String.Format("showControls->{0}", showControls.ToString()));

            lblSocialAFSVisitLocations.Visible = showControls;
            //lstSocialAFSOffices.Visible = showControls;
            ddSocialAFSOffices.Visible = showControls;

            lblSocialForeignNational.Visible = showControls;
            ddSocialForeignNationalYesOrNo.Visible = showControls;

            lblSocialForeignName.Visible = showControls;
            txtSocialForeignNationalEmail.Visible = showControls;

            if (!showControls)
            {
                ddSocialAFSOffices.SelectedIndex = -1;
                ddSocialForeignNationalYesOrNo.SelectedIndex = -1;
                txtSocialForeignNationalEmail.Text = "";
            }
        }
        #endregion

        #region Event Handlers
        // Occurs before the form region is displayed.      
        private void RequestDetailsFormRegion_FormRegionShowing(object sender, System.EventArgs e)
        {
            try
            {
                //AppointmentItem appointmentItem;

                //if (this.OutlookItem is Outlook.AppointmentItem)
                //{
                //    appointmentItem = (Outlook.AppointmentItem)this.OutlookItem;
                //    Initialize(appointmentItem);
                //}
                //else if (this.OutlookItem is Outlook.MeetingItem)
                //{
                //    appointmentItem = ((Outlook.MeetingItem)this.OutlookItem).GetAssociatedAppointment(false);
                //    Initialize((appointmentItem);
                //}

                // Only expect to show form on load if it's a meeting invite in someone's inbox.
                if (this.OutlookItem is Outlook.MeetingItem)
                {
                    AppointmentItem appointmentItem;
                    appointmentItem = ((Outlook.MeetingItem)this.OutlookItem).GetAssociatedAppointment(false);

                    if (appointmentItem.ItemProperties[Property.AFSRequestItem] != null && (bool)appointmentItem.ItemProperties[Property.AFSRequestItem].Value == true)
                        Initialize(appointmentItem);
                    else
                    {
                        this.Visible = false;
                        this.OutlookFormRegion.Visible = false;
                    }
                }
                else
                {
                    this.Visible = false;
                    this.OutlookFormRegion.Visible = false;
                }
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex.ToString());
                MessageBox.Show(ErrorMessages.ProgramException);
            }

            //Globals.FormRegionLoaded = true;
        }

        // Occurs when the form region is closed.
        private void RequestDetailsFormRegion_FormRegionClosed(object sender, System.EventArgs e)
        {
            //SaveRequestDetailsToLocalOutlookItemProperties();
            Logger.Verbose("Entering");
        }

        private void AppointmentItem_PropertyChange(string Name)
        {
            Logger.Info("Entered AppointmentItem_PropertyChange");
            Logger.Info(String.Format("Name: {0}", Name));
            //Globals.ThisAddIn.Application.ActiveInspector().CurrentItem
        }

        private void lstVisitType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Outlook.AppointmentItem appointmentItem = (Outlook.AppointmentItem)this.OutlookItem;

            //appointmentItem.ItemProperties[Variables.VisitType].Value = lstVisitType.SelectedValue;

            if (lstVisitType.SelectedItems.Count > 0)
            {
                TabCtrl.TabPages.Clear();
                TabCtrl.TabPages.Add(TabPage1);

                if (String.Compare(Utility.GetStringValueFromObject(lstVisitType.SelectedItem), General.VisitTypeSocialVisitRequest, true) == 0)
                {
                    TabCtrl.TabPages.Add(TabPage3);
                    TabPage3.Show();
                    TabCtrl.SelectTab(General.TabIndexThree);
                }
                else
                {
                    TabCtrl.TabPages.Add(TabPage2);
                    TabPage2.Show();
                    TabCtrl.SelectTab(General.TabIndexTwo);
                }
            }
        }

        private void lstVisitLocations_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstVisitLocations.SelectedItems.Count > 0)
            {
                string[] visitLocationsArray = new string[lstVisitLocations.SelectedItems.Count];

                for (Int16 i = 0; i <= (lstVisitLocations.SelectedItems.Count - 1); i++)
                {
                    visitLocationsArray[i] = lstVisitLocations.SelectedItems[i].ToString();
                }

                if (lstVisitLocations.SelectedIndex == 0)
                {
                    ShowAFSControls(true);
                }
                else
                {
                    ShowAFSControls(false);
                }
            }
            else
            {
                ShowAFSControls(false);
            }

        }

        private void lstVisitLocationsSocial_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstSocialVisitLocations.SelectedItems.Count > 0)
            {
                string[] visitLocationsArray = new string[lstSocialVisitLocations.SelectedItems.Count];

                for (Int16 i = 0; i <= (lstSocialVisitLocations.SelectedItems.Count - 1); i++)
                {
                    visitLocationsArray[i] = lstSocialVisitLocations.SelectedItems[i].ToString();
                }

                if (lstSocialVisitLocations.SelectedIndex == 0)
                {
                    ShowAFSControlsSocial(true);
                }
                else
                {
                    ShowAFSControlsSocial(false);
                }
            }
            else
            {
                ShowAFSControls(false);
            }
        }

        private void ddForeignNationalYesOrNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddForeignNationalYesOrNo.SelectedItem.ToString() == "Yes")
            {
                txtForeignNationalEmail.Enabled = true;
            }
            else
            {
                txtForeignNationalEmail.Text = "";
                txtForeignNationalEmail.Enabled = false;
            }
        }

        private void chkExistingVisit_CheckedChanged(object sender, EventArgs e)
        {
            //if (chkExistingVisit.Checked)
            //{
            //    lblPreviousVisit.Visible = true;
            //    txtPreviousVisitId.Visible = true;
            //}
            //else
            //{
            //    lblPreviousVisit.Visible = false;
            //    txtPreviousVisitId.Visible = false;
            //}
        }

        private void ddConfirmNoSensitiveShared_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddConfirmNoSensitiveShared.SelectedItem.ToString() == "Will be shared")
            //{
            //    txtBusinessSharedExplanation.Enabled = true;
            //}
            //else
            //{
            //    txtBusinessSharedExplanation.Enabled = false;
            //}

        }

        private void TabCtrl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TabCtrl.SelectedIndex == 0)
            {
                lstVisitType.SelectedItems.Clear();

                TabCtrl.TabPages.Remove(this.TabPage2);
                TabCtrl.TabPages.Remove(this.TabPage3);
            }
        }

        private void ddSocialForeignNationalYesOrNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddSocialForeignNationalYesOrNo.SelectedItem.ToString() == "Yes")
            {
                txtSocialForeignNationalEmail.Enabled = true;
            }
            else
            {
                txtSocialForeignNationalEmail.Text = "";
                txtSocialForeignNationalEmail.Enabled = false;
            }
        }
        #endregion
    }
}
